<?php

    class ApiController extends Controller {
        /**
         * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
         * using two-column layout. See 'protected/views/layouts/column2.php'.
         */
        public $layout = '//layouts/column3';
        public $logo='';
        /**
         * @return array action filters
         */
        public function filters() {
            return array(
                'accessControl', // perform access control for CRUD operations
                'postOnly + delete', // we only allow deletion via POST request
            );
        }

        /**
         * Specifies the access control rules.
         * This method is used by the 'accessControl' filter.
         * @return array access control rules
         */
        public function accessRules() {
            return array(
                array('allow', // allow all users to perform 'index' and 'view' actions 
                    'actions' => array('auth', 'ping', 'login','login_form', 'portal', 'verify_mobile','verify_login','template','test','wxlogin','applogin','moreGraphic','moreView'), 
                    'users' => array('*'),
                ),
                array('deny', // deny all users
                    'users' => array('*'),
                ),
            );
        }

        /**
         * 验证接口，二次认证的接口
         */
        public function actionAuth() {
            // todo 将auth所有的参数都处理
            $token = $_GET['token'];
            $stage = $_GET['stage'];
            $mac = $_GET['mac'];
            
            $ip = $_GET['ip'];

            $user =User::model()->find('token=:token', array(':token' => $token));
            if (empty($user)) {
                // error_log("Auth = 0");
                // 没有找到用信息
                echo 'Auth: 0';
                return;
            } 
            
            $publicip = $this->getIP();
            $gateway = Gateway::model()->find('publicip=\''.$publicip.'\' order by id desc');

            // $connectionlog = Connectionlog::model()->find('userid='.$user->id.' order by id desc');
            $online = new Onlinelog();
            $online->companyid = $gateway->companyid;
            $online->gatewayid = $gateway->id;
            $online->userid = $user->id;
           

            if($stage == 'counters'){
              
                //用当前时间减去上一次更新时间
                $nowtime = date('Y-m-d H:i:s');

                $uptime = strtotime($nowtime) - strtotime($user->lasttime);

                $user->uptime = $user->uptime + $uptime;
                $user->lasttime = $nowtime;
                $online->duration = $uptime;
                $user->save();


            }else if($stage == 'login'){

                $user->mac = $mac;
                $user->ip = $ip;

                $user->lasttime = date('Y-m-d H:i:s');
                $online->duration = 0;
                $user->save();

            }

            $online->save();
            error_log("Auth = 0");
            // 验证成功
            echo 'Auth: 1';
            
            exit;
        }
       
        /**
         * ping 更新路由器在线时间
         * todo 加入有路由连接，但没有数据的情况的通知和记录
         */
        public function actionPing() {
            // header('Content-type: application/json;charset=utf-8');
            //  更新路由器在线时间
            // $gatewayname = empty($_GET['gw_id']) ? 'default':$_GET['gw_id'];
            if (!empty($_GET['gw_id']) ){ 
                $lasttime = date('Y-m-d H:i:s',time());
                Gateway::model()->updateAll(array('lasttime'=>$lasttime),'gatewayname=:gatewayname',array(':gatewayname'=>$_GET['gw_id']));
            }
            echo 'Pong';
        }

        /**
         * 用户登陆.
         * @param integer $id the ID of the model to be updated
         * 登陆页面的优化的css内链
         */
        public function actionLogin() {  
            if (empty($_REQUEST['gw_id'])){
                throw new CHttpException(404,"没有得到路由器名称");
            }
            if($_REQUEST['gw_id']=='previewshowcompany'){
                 $this->redirect(array('template','cid'=>$_REQUEST['companyid'],'tid'=>$_REQUEST['template'],));
            } 
 
            if(empty($_REQUEST['gw_address']) || empty($_REQUEST['gw_port'])){
                throw new CHttpException(404,"没有得到地址和端口");
            }  

            //取得路由器信息 
            $gy = Gateway::model()->find('gatewayname=:gatewayname',array(':gatewayname'=>$_REQUEST['gw_id']));
 
            if(empty($gy)){
                throw new CHttpException(404,'没有该路由器');
            }
            
            //将传递的信息放入到session中 
            Yii::app()->session->add('gw_id',$_REQUEST['gw_id']);
            Yii::app()->session->add('gw_address',$_REQUEST['gw_address']);
            Yii::app()->session->add('gw_port',$_REQUEST['gw_port']);
            Yii::app()->session->add('url',empty($_REQUEST['url'])?"":$_REQUEST['url']);

            Yii::app()->session->add('gw_gatewayid',$gy->id);
            Yii::app()->session->add('gw_companyid',$gy->companyid);
            Yii::app()->session->add('gw_gatewayname',$gy->gatewayname);



            // 记录路人信息
        
            $lastlog = Linklog::model()->count('mac =:mac and createtime > :time', array('mac'=>$_REQUEST['mac'] , 'time'=>date('Y-m-d H:i:s', strtotime("- 5 minute")) ) );

            if ($lastlog <= 0) {
                $guest = new Linklog();
                $guest->companyid = $gy->companyid;
                $guest->gatewayid = $gy->id;
                $guest->mac = $_REQUEST['mac'];
                $guest->save();
                //更新路由器IP
                $publicip = $this->getIP();
                $privateip = $_GET['gw_address'];

                if(!($gy->publicip == $publicip) || !($gy->privateip == $privateip) ){
                    $gy->publicip = $publicip;
                    $gy->privateip = $privateip;
                    $gy->save();
                }
            }
 
            $this->redirect(array('template', 'cid'=> $gy->companyid ,));
        }
 
        public function actionTest(){
            
            $templateid = '';
            if (!empty($_GET["tid"])) {
                $templateid = $_GET["tid"] ;
            } 

            // $this->redirect(array('login', 'companyid'=>'1' , 'gw_id' =>'previewshowcompany','template'=>$templateid));

            // $this->redirect(array('login', 'cid'=>'1' , 'gw_id' =>'default','gw_address'=>'192.168.9.1' ,'gw_port'=>'2060','url'=>"http://www.163.com"));
             $this->redirect(array('login', 'cid'=>'3' , 'gw_id' =>'youdao1','gw_address'=>'192.168.9.1' ,'gw_port'=>'2060','mac'=>'12:32:33:33:33:3e','url'=>"http://www.163.com"));

            // header('HTTP/1.1 302 Moved Permanently');
            // // header("Location: http://www.baidu.com");
            // header("Location: http://192.168.9.1:2060/wifidog/auth?token=1234567890");

        }
        /**
        ** 0 login
        *  1 movie
        *  2 图片轮播图
        *  10 - * index
        **
        **/
        public function actionTemplate($cid){
            $company = Company::model()->findByPk($cid);  
            // var_dump($company);return;
            $templateid = $company->template;
            if (isset($_GET["tid"])) {
                $templateid = $_GET["tid"] ;
            }  

            switch ($templateid)
            {
                case 0:    
                     $model = new User();
                     $category=Category::model()->findAll('categorytype=:categorytype',array(':categorytype'=>'电影'));
                     $videoCategory=array();
                     foreach ($category as $key => $value) {
                         $videoCategory[]=$value['id'];
                     }  
                    $category=Category::model()->findAll('categorytype=:categorytype',array(':categorytype'=>'应用'));
                     $appCategory=array();
                     foreach ($category as $key => $value) {
                         $appCategory[]=$value['id'];
                     } 
                    
                    $video = Video::model()->findAllBySql('select * from '.Video::model()->tableName().' where categoryid in ('.implode(',',$videoCategory).') order by orderby desc,createtime desc limit 3'); 
                     
                    $app = Video::model()->findAllBySql('select * from '.Video::model()->tableName().' where categoryid in ('.implode(',',$appCategory).') order by orderby desc,createtime desc limit 3'); 
                    
                    $company = Company::model()->find(' id=:id',array(':id'=>$cid)); 

                    $this->render('login_form', array('model' => $model,'video'=>$video,'app'=>$app,'company'=>$company));  
                    break;
                case 1:
                    // echo "movie";
                    $model = Xdvert::model()->find('companyid='.$cid.' and usable = 1 and xdtype = 1 ',array('order'=>'id')); 
                    $this->renderPartial('movie', array('model' => $model),false, true);
                    break;
                case 2:
                     $model = Xdvert::model()->findAll(' companyid='.$cid.' and usable = 1 and xdtype = 0',array('order'=>'id'));
                     $this->renderPartial('carousel', array('model' => $model),false, true);
                    break;
                case 10: 
                    $company = Company::model()->find(' id=:id',array(':id'=>$cid));

                    $xdvert = Xdvert::model()->findAll(' companyid=:companyid and usable = 1 and xdtype = 2',array(':companyid'=>$cid));

                    $productcolumn=Column::model()->findAll('categorytype=:categorytype and companyid=:companyid ',array(':categorytype'=>'1',':companyid'=>$cid));

                    $productColumn=array();
                    foreach ($productcolumn as $key => $value) {
                         $productColumn[]=$value['id'];
                    }

                    $articlecolumn=Column::model()->findAll('categorytype=:categorytype and companyid=:companyid ',array(':categorytype'=>'0',':companyid'=>$cid));
                    $articleColumn=array();
                    foreach ($articlecolumn as $key => $value) {
                         $articleColumn[]=$value['id'];
                    }

                    $product = Article::model()->findAllBySql('select * from '.Article::model()->tableName().' where columnid in ('.implode(',',$productColumn).') order by orderby desc,createtime desc limit 8');

                    $article = Article::model()->findAllBySql('select * from '.Article::model()->tableName().' where columnid in ('.implode(',',$articleColumn).') order by orderby desc,createtime desc limit 3');

                    $this->renderPartial('portal_fresh', array('company'=>$company,'xdvert'=>$xdvert,'article'=>$article,'product'=>$product),false, true);
                    break;
                case 11:
                     $company = Company::model()->find(' id=:id',array(':id'=>$cid));
                     $models= CompanyExtend::model()->findAll("companyid=:companyid and type=:type",array(":companyid"=>$cid,":type"=>"weixin"));
                     $model=array();  
                     foreach ($models as $key => $value) {
                         $model[$value->keys]=$value->values;
                     }  
                     $this->renderPartial('weixin', array('model' => $company,'weixin'=>$model),false, true);
                    break;
                case 12:
                     $company = Company::model()->find(' id=:id',array(':id'=>$cid));
                     $models= CompanyExtend::model()->findAll("companyid=:companyid and type=:type",array(":companyid"=>$cid,":type"=>"appdownload"));
                     $model=array();  
                     foreach ($models as $key => $value) {
                         $model[$value->keys]=$value->values;
                     } 
                     $this->renderPartial('appdownload', array('model' => $company,'appdownload'=>$model),false, true);
                    break; 
 
                case 13: 
                     $company = Company::model()->find(' id=:id',array(':id'=>$cid));
                     $xdvert = Xdvert::model()->findAll(' companyid=:companyid and usable = 1 and xdtype = 2',array(':companyid'=>$cid));  
                    
                     $articlecolumn=Column::model()->findAll('categorytype=:categorytype and companyid=:companyid ',array(':categorytype'=>'0',':companyid'=>$cid));
                     $articleColumn=array();
                     foreach ($articlecolumn as $key => $value) {
                         $articleColumn[]=$value['id'];
                     } 
                     
                     $article = Article::model()->findAllBySql('select * from '.Article::model()->tableName().' where columnid in ('.implode(',',$articleColumn).') order by orderby desc,createtime desc limit 5');  
                    
                     $this->renderPartial('portal_medical', array('company'=>$company,'xdvert'=>$xdvert,'article'=>$article),false, true);
                     
                    break;
                case 14:  
                     $company = Company::model()->find(' id=:id',array(':id'=>$cid));

                     $xdvert = Xdvert::model()->findAll(' companyid=:companyid and usable = 1 and xdtype = 2',array(':companyid'=>$cid));

                    $criteria = new CDbCriteria(); 
                    $criteria->compare('companyid', $cid);
                    $criteria->compare('usable', 1);
                    $criteria->compare('xdtype', 3);
                    $criteria->order = 'id desc';
                    $criteria->limit = 3;

                     $xdvert_video = Xdvert::model()->findAll($criteria);   

                     $this->renderPartial('portal_fresh4s', array('company'=>$company,'xdvert'=>$xdvert,'xdvert_video'=>$xdvert_video),false, true);
                     break; 
                default:
                    echo "No number between 1 and 3";
            }
        }
 

        /**
        * 门户首页的更多页面
        * @param void
        * @return void
        **/
        public function actionMoreGraphic($cid,$type,$view){
            $company = Company::model()->find(' id=:id',array(':id'=>$cid));
            if($type=='1'){
                $productcolumn=Column::model()->findAll('categorytype=:categorytype and companyid=:companyid ',array(':categorytype'=>'1',':companyid'=>$cid));
                $productColumn=array();
                foreach ($productcolumn as $key => $value) {
                    $productColumn[]=$value['id'];
                }
                $views = Article::model()->findAllBySql('select * from '.Article::model()->tableName().' where columnid in ('.implode(',',$productColumn).') order by orderby desc,createtime desc');
            }else if($type=='0'){
                $articlecolumn=Column::model()->findAll('categorytype=:categorytype and companyid=:companyid ',array(':categorytype'=>'0',':companyid'=>$cid));
                $articleColumn=array();
                foreach ($articlecolumn as $key => $value) {
                    $articleColumn[]=$value['id'];
                 }
                $views = Article::model()->findAllBySql('select * from '.Article::model()->tableName().' where columnid in ('.implode(',',$articleColumn).') order by orderby desc,createtime desc');
            }else if($type=='2'){ 
                $views = Xdvert::model()->findAll(' companyid=:companyid and usable = 1 and xdtype = 3',array(':companyid'=>$cid));
            }
            if($view == '0'){
                $viewpage= 'portal_all_more';
            }else if($view == '1'){
                $viewpage= 'portal_medical_more';
            }else if($view == '2'){
                $viewpage= 'portal_video_more';
            }

            $this->renderPartial($viewpage, array('company'=>$company,'views'=>$views),false, true);
        }

        /**
        * 门户首页的详细
        * @param void
        * @return void
        **/
        public function actionMoreView($cid,$vid,$view){
            $company = Company::model()->find(' id=:id',array(':id'=>$cid)); 
             if($view == '0'){
                  $model = Article::model()->find('id =:id',array(':id'=>$vid));
                $viewpage= 'portal_all_view';
            }else if($view == '1'){
                  $model = Article::model()->find('id =:id',array(':id'=>$vid));
               $viewpage= 'portal_medical_view';
            }else if($view == '2'){
                $model = Xdvert::model()->find('id =:id',array(':id'=>$vid));
                $viewpage= 'portal_video_view';
            } 
            $this->renderPartial($viewpage, array('company'=>$company,'model'=>$model),false, true);
        }
        /**
         * 登陆界面
         *
         * @return void
         * @author 
         **/ 
        public function actionLogin_form() { 

            if(empty(Yii::app()->session['gw_id']) || empty(Yii::app()->session['gw_address']) || empty(Yii::app()->session['gw_port'])){
                throw new CHttpException(404, "参数不正确，请重新登录");
            }
            //取得路由器信息 
            $gy = Gateway::model()->find('gatewayname=:gatewayname',array(':gatewayname'=>Yii::app()->session['gw_id'])); 

            if(empty($gy)){
                throw new CHttpException(404,'没有找到路由器');
            }
            $company= $gy->company;
            // $category=Category::model()->findAll('categorytype=:categorytype',array(':categorytype'=>'电影'));
            //  $videoCategory=array();
            //  foreach ($category as $key => $value) {
            //      $videoCategory[]=$value['id'];
            //  }
            // $category=Category::model()->findAll('categorytype=:categorytype',array(':categorytype'=>'应用'));
            //  $appCategory=array();
            //  foreach ($category as $key => $value) {
            //      $appCategory[]=$value['id'];
            //  }

            // $video = Video::model()->findAll('categoryid in ('.implode(',',$videoCategory).')',array('order'=>'hit desc','limit' => 3));

            // $app = Video::model()->findAll('categoryid in ('.implode(',',$appCategory).')',array('order'=>'downloads desc','limit' => 3));
            //$xdvert = Xdvert::model()->findAll(' companyid=:companyid',array(':companyid'=>$gy->companyid)); 
            $model = new User();
            $this->render('login_form', array('model' => $model,'video'=>array(),'app'=>array(),'company'=>$company));
            // $this->render('login_form', array('model' => $model,'video'=>$video,'app'=>$app));

        }

        //验证用户登陆
        public function actionVerify_login(){
            //1>验证用户是否可用
            $userModel = User::model()->find('mobile=:mobile ', array(':mobile' => $_POST['User']['mobile']));

            if (empty($userModel) || strcasecmp($userModel->password , $_POST['User']['password'])) {
                $model = new User();
                $model->mobile=$_POST['User']['mobile'];
                $errormessage="手机号和密码不匹配!请重新输入";
                return $this->render('login_form', array('model' => $model,'errormessage'=>$errormessage));
            }

            $userModel->attributes = $_POST['User'];
            $userModel->token = empty($userModel->token) ? md5(Yii::app()->params['private_key'] . $userModel->mobile . $userModel->password) : $userModel->token;
            $userModel->comeing = $userModel->comeing+1;
            $userModel->save();

            //2>添加connectionlog 表           

            Yii::app()->format->datetimeFormat='Y-m-d H:i:s';

            $connectionlog = new Connectionlog();
            $connectionlog->userid = $userModel->id;
            $connectionlog->companyid = Yii::app()->session['gw_companyid'];
            $connectionlog->gatewayid = Yii::app()->session['gw_gatewayid'];
            $connectionlog->gatewayname = Yii::app()->session['gw_gatewayname'];

            $connectionlog->mobile = $userModel->mobile;
            $connectionlog->createtime =  Yii::app()->format->formatDateTime(time());
            $connectionlog->save();

            //添加or更新企业和用户表信息
            $this->saveCompanyUser($userModel->id, Yii::app()->session['gw_companyid']);

            //3>发送请求到auth 
            $url = "http://".Yii::app()->session['gw_address'].":".Yii::app()->session['gw_port']."/wifidog/auth?token=".$userModel->token;

            if (strpos($_SERVER["HTTP_USER_AGENT"] , 'UCB') ){
                echo '<html><head><meta http-equiv="refresh" content="0;url='.$url.'"></head><body><div style="width:100%;padding-top:50px;text-align: center;">loading...</div></body></html>';
            }else{
                header('HTTP/1.1 302 Moved Permanently');
                header("Location: ".$url);
            }
        }

        /**
         * @return bool
         * 发送密码到手机 ，添加用户信息，用户名，密码，md5生成token（私有key）
         */
        public function actionVerify_mobile() {
            //1>验证用户是否可用
            if (empty($_REQUEST['mobile']) || empty(Yii::app()->session['gw_id'])) return;
            
            $mobile = $_REQUEST['mobile'];

            //3>验证黑名单 (通过企业ID和手机号码进行验证)
            $companyid = Yii::app()->session['gw_companyid'];

            $blacklist = CompanyBlacklist::model()->count(' companyid=:companyid and mobile=:mobile',array(':companyid'=>$companyid ,':mobile'=>$mobile));

            if($blacklist > 0){
                echo json_encode(array('code' => 4,  'message' => "用户已被禁用"));
                exit; 
            }

            $isUser = User::model()->find('mobile=:mobile', array(':mobile' => $mobile));
            $env = '';
  
            // 用户已注册
            if (!empty($isUser)) {
                if (empty($isUser->token)) {
                    echo json_encode(array('code' => 3, 'res' =>$isUser->password, 'message' => "密码通过短信已发送，请输入密码开始免费上网"));
                } else {
                    echo json_encode(array('code' => 2, 'res' => $isUser->password, 'message' => "用户已注册，请直接点击开始免费上网"));
                }
                exit;
            } 
            //第一次注册
            $newPassword = $this->random(4);
            //添加用户信息
            $user = new User();
            $user->mobile = $mobile;
            $user->password = $newPassword;

            $company = Company::model()->find('id=:id',array(':id'=>$companyid));
            if ($user->save()) {
                //添加成功发送短信
                $content='欢迎使用'.$company->title.'免费网络，验证码:'.$newPassword.'，【'.$company->title.'】';
                //判断企业是否设置短信营销的内容
                $smsmarket=Smsmarket::model()->find('companyid=:companyid',array(':companyid'=>$companyid));  
                if(!empty($smsmarket) && $smsmarket->newusers!=""){
                     $content=$smsmarket->newusers.' 验证码:'.$newPassword.'，【'.$company->title.'】';
                }

                $this->sendSMS($mobile , $content, $companyid ,$user->id);
                echo json_encode(array('code' => 0,'res'=>$newPassword,'message' => "密码已发送，请注意查收..."));
            } else {
                echo json_encode(array('code' => 1, 'message' => "发送失败，请尝试重新登录"));
            } 
        }

        /**
         * 活动列表
         * 二期要做的是把来路URL用起来。
         * 门户的链接和广告位。
         * 门户页面的代码优化和css内链
         */
        public function actionPortal() { 
              //取得路由器信息 
            $gy = Gateway::model()->find('gatewayname=:gatewayname',array(':gatewayname'=>$_REQUEST['gw_id']));
            $company= $gy->company;
            if($company->template==12){
                $models= CompanyExtend::model()->findAll("companyid=:companyid and type=:type",array(":companyid"=>$company->id,":type"=>"appdownload"));
                $model=array();  
                foreach ($models as $key => $value) {
                    $model[$value->keys]=$value->values;
                } 
                if (stripos($_SERVER["HTTP_USER_AGENT"],'android') || stripos($_SERVER["HTTP_USER_AGENT"],'window') ){
                    return $this->redirect($model['appandroidurl']); 
                }else {
                    return $this->redirect($model['appiosurl']);  
                } 
            }else{
                if(!empty($company->portalurl)){
                     return $this->redirect($company->portalurl); 
                }else{
                    $url = 'http://www.hao123.com';
                    return $this->redirect($url); 
                }
            } 
        }
 
        /**
         * 通过微信关注后,生成连接登陆
         **/
        public function actionWxlogin($code)
        {  
            if(strlen($code)!=33){
                throw new CHttpException(404);
            }
            //得到企业id
            $companyid=substr($code,32); 
            //取得路由器信息 
            $publicip = $this->getIP(); 
            $gateway = Gateway::model()->find('publicip=:publicip',array(':publicip'=>$publicip)); 

            if(empty($gateway)){
                throw new CHttpException(404);
            }

            //创建用户
            $user = new User();
            $user->mobile = time().'_wx';
            $user->password = $this->random(4);
            $user->token = md5(Yii::app()->params['private_key'] . $user->mobile . $user->password) ;
            $user->comeing = 1; 
            $user->save(); 

            //插入到企业和用户关系表
            $this->saveCompanyUser($user->id, $companyid);

            //插入到登陆日志
            Yii::app()->format->datetimeFormat='Y-m-d H:i:s'; 
            $connectionlog = new Connectionlog();
            $connectionlog->userid = $user->id;
            $connectionlog->companyid = $companyid;
            $connectionlog->gatewayid = $gateway->id;
            $connectionlog->gatewayname = $gateway->gatewayname; 
            $connectionlog->mobile = $user->mobile;
            $connectionlog->createtime =  Yii::app()->format->formatDateTime(time());
            $connectionlog->save();  
            //返回到路由的认证服务 
            $url = "http://".$gateway->privateip.":2060/wifidog/auth?token=".$user->token;
             
            if (strpos($_SERVER["HTTP_USER_AGENT"] , 'UCB') ){
                echo '<html><head><meta http-equiv="refresh" content="0;url='.$url.'"></head><body><div style="width:100%;padding-top:50px;text-align: center;">loading...</div></body></html>';
            }else{
                header('HTTP/1.1 302 Moved Permanently');
                header("Location: ".$url);
            } 
        }

         /**
         * 通过应用下载后,生成连接登陆
         **/
        public function actionApplogin($code)
        { 
            if(strlen($code)!=33){
                throw new CHttpException(404);
            }
            //得到企业id
            $companyid=substr($code,32); 
            //取得路由器信息 
            $publicip = $this->getIP(); 
            $gateway = Gateway::model()->find('publicip=:publicip',array(':publicip'=>$publicip)); 

            if(empty($gateway)){
                throw new CHttpException(404);
            }

            //创建用户
            $user = new User();
            $user->mobile = time().'_app';
            $user->password = $this->random(4);
            $user->token = md5(Yii::app()->params['private_key'] . $user->mobile . $user->password) ;
            $user->comeing = 1; 
            $user->save(); 

            //插入到企业和用户关系表
            $this->saveCompanyUser($user->id, $companyid);

            //插入到登陆日志
            Yii::app()->format->datetimeFormat='Y-m-d H:i:s'; 
            $connectionlog = new Connectionlog();
            $connectionlog->userid = $user->id;
            $connectionlog->companyid = $companyid;
            $connectionlog->gatewayid = $gateway->id;
            $connectionlog->gatewayname = $gateway->gatewayname; 
            $connectionlog->mobile = $user->mobile;
            $connectionlog->createtime =  Yii::app()->format->formatDateTime(time());
            $connectionlog->save();  
            //返回到路由的认证服务 
            $url = "http://".$gateway->privateip.":2060/wifidog/auth?token=".$user->token;
             
            if (strpos($_SERVER["HTTP_USER_AGENT"] , 'UCB') ){
                echo '<html><head><meta http-equiv="refresh" content="0;url='.$url.'"></head><body><div style="width:100%;padding-top:50px;text-align: center;">loading...</div></body></html>';
            }else{
                header('HTTP/1.1 302 Moved Permanently');
                header("Location: ".$url);
            } 
        }



        //插入到企业与用户的表
        private function saveCompanyUser($userid,$companyid){
             Yii::app()->format->datetimeFormat='Y-m-d H:i:s'; 
            $companyUser = CompanyUser::model()->find('userid=:userid and companyid=:companyid ',array(':userid'=>$userid,':companyid'=>$companyid));
            if(empty($companyUser)){
                $model=new CompanyUser();
                $model->userid=$userid;
                $model->companyid =$companyid; 
                $model->lastsendtime = Yii::app()->format->formatDateTime(time());
                $model->save(); 
            }else{ 
                //判断企业是否设置短信营销的欢迎老用户的内容
                $smsmarket=Smsmarket::model()->find('companyid=:companyid',array(':companyid'=>$companyid));  
                if(!empty($smsmarket) && $smsmarket->oldsendstatus == 1 && $smsmarket->oldusers !=''){
                    $company = Company::model()->find('id=:id',array(':id'=>$companyid));
                    $user = User::model()->find('id=:id',array(':id'=>$userid)); 
                    $content=$smsmarket->oldusers.' 【'.$company->title.'】';
                    $this->sendSMS($user->mobile,$content,$company->companyid,$user->id);

                    $commpanyUser->lastsendtime = Yii::app()->format->formatDateTime(time());
                }
               
                //$commpanyUser->lasttime = Yii::app()->format->formatDateTime(time());
                $companyUser->save();
            }
        }

        //给用户发送短信
        private function sendSMS($mobile,$content,$companyid,$userid){
             $lines=ceil($this->utf8_strlen($content)/50);  
            if(Yii::app()->params['env'] == 'main'){
                if(!(Company::model()->isSend($companyid,$lines))){
                    echo json_encode(array('code' => 1,'message' => "商家费用不足,请联系商家"));
                    exit;
                } 
                 $res = User::model()->sendSMS($mobile,$content);
                 if($res =='success'){
                    Company::model()->deductions($companyid,$lines);
                    //记录到发送短信的日志表中
                     Yii::app()->format->datetimeFormat='Y-m-d H:i:s';
                     $sendsmslog = new Sendsmslog();
                     $sendsmslog->userid=$userid;
                     $sendsmslog->companyid=$companyid;
                     $sendsmslog->mobile=$mobile;
                     $sendsmslog->sended=1;
                     $sendsmslog->content=$content;
                     $sendsmslog->createtime=Yii::app()->format->formatDateTime(time());
                     $sendsmslog->save();
                 } 
            } 
        }

        //生成密码  todo 改成4位
        private function random($len) {
            $srcstr = "1234567890";
            mt_srand();
            $strs = "";
           $strlen= strlen($srcstr) - 1 ;
            for ($i = 0; $i < $len; $i++) {
                $strs .= $srcstr[mt_rand(0,$strlen )];
            }
            return strtoupper($strs);
        }

        /**
         * 得到字符串长度
         * 
         **/  
        private function utf8_strlen($string = null) 
        {
            // 将字符串分解为单元
            preg_match_all("/./us", $string, $match);
            // 返回单元个数
            return count($match[0]);
        }
 
        /**
        * 获得IP地址
        */
        private function getIP()
        {
            if (isset($_SERVER['HTTP_CLIENT_IP']) and !empty($_SERVER['HTTP_CLIENT_IP']))
            {
                return $_SERVER['HTTP_CLIENT_IP'];
            }
            if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) and !empty($_SERVER['HTTP_X_FORWARDED_FOR']))
            {
                return strtok($_SERVER['HTTP_X_FORWARDED_FOR'], ',');
            }
            if (isset($_SERVER['HTTP_PROXY_USER']) and !empty($_SERVER['HTTP_PROXY_USER']))
            {
                return $_SERVER['HTTP_PROXY_USER'];
            }
            if (isset($_SERVER['REMOTE_ADDR']) and !empty($_SERVER['REMOTE_ADDR']))
            {
                return $_SERVER['REMOTE_ADDR'];
            }
            else
            {
                return "0.0.0.0";
            }
        }

    }
